package com.gitee.melin.bee.core.jdbc.dialect.inceptor;

import com.gitee.melin.bee.core.jdbc.dialect.DefaultTypeConvertor;
import com.gitee.melin.bee.core.jdbc.relational.ConnectionInfo;
import com.gitee.melin.bee.core.jdbc.enums.DataSourceType;
import com.gitee.melin.bee.core.jdbc.dialect.DataTypeConvertor;
import com.gitee.melin.bee.core.jdbc.dialect.AbstractJdbcDialect;
import com.gitee.melin.bee.core.jdbc.dialect.IDBQuery;
import com.gitee.melin.bee.core.jdbc.dialect.hive.HiveQuery;
import org.apache.commons.lang3.StringUtils;

import java.sql.Connection;
import java.sql.Driver;

public class InceptorJdbcDialect extends AbstractJdbcDialect {

    @Override
    public DataSourceType getDataSourceType() {
        return DataSourceType.INCEPTOR;
    }

    public InceptorJdbcDialect(ConnectionInfo connectionInfo) {
        super(connectionInfo);
    }

    public InceptorJdbcDialect(Connection connection) {
        super(connection);
    }

    @Override
    protected IDBQuery getDBQuery() {
        return new HiveQuery();
    }

    @Override
    protected DataTypeConvertor getTypeConvert() {
        return new DefaultTypeConvertor();
    }

    @Override
    protected Driver getDriver() {
        return loadDriver(DataSourceType.INCEPTOR.getDriverClass());
    }

    @Override
    protected String getDDLColumnName() {
        return "";
    }

    @Override
    protected String getJdbcUrl() {
        String jdbcUrl = this.connectionInfo.getJdbcUrl();
        if (StringUtils.isNotBlank(this.connectionInfo.getPrincipal()) ||
                StringUtils.isNotBlank(this.connectionInfo.getKrb5File()) ||
                StringUtils.isNotBlank(this.connectionInfo.getKeytabFile())) { // kerberos 认证

            if (!StringUtils.contains(jdbcUrl, ";principal=")) {
                jdbcUrl = jdbcUrl + ";principal=" + this.connectionInfo.getPrincipal();
            }

            jdbcUrl = jdbcUrl + ";authentication=kerberos";
            jdbcUrl = jdbcUrl + ";kuser=" + this.connectionInfo.getPrincipal();
            jdbcUrl = jdbcUrl + ";keytab=" + this.connectionInfo.getKeytabFile();
            jdbcUrl = jdbcUrl + ";krb5conf=" + this.connectionInfo.getKrb5File();
        }

        return jdbcUrl;
    }
}
